import {createRouter, createWebHistory} from 'vue-router';
import {type RouteRecordRaw} from 'vue-router'
import TransferRecord from '../components/TransferRecord.vue';
import StoreManage from "../components/StoreManage.vue";
import {DataAnalysis, Suitcase, Switch, Search, Shop} from "@element-plus/icons-vue";
import Login from "../components/Login.vue";
import {useAuthStore} from "../stores/auth.ts";
import {TOKEN_KEY} from "../utils/auth.ts";
import SalesBI from "../components/SalesBI.vue"; // 导入登录状态工具

const currentMode = import.meta.env.MODE;
const released = (currentMode === "production");

// 定义路由规则
const routes: RouteRecordRaw[] = [
    {
        path: '/',
        name: '销售分析',
        component: SalesBI,
        meta: {
            title: "销售分析",
            icon: DataAnalysis,
            requiresAuth: released,
            hideInBreadcrumb: true
        }
    },
    {
        path: '/transactions',
        name: '转账记录',
        component: TransferRecord,
        meta: {
            title: "转账记录",
            icon: Switch,
            requiresAuth: released,
            hideInBreadcrumb: true
        }
    },
    {
        path: '/store-manage',
        name: '药店管理',
        component: StoreManage,
        meta: {
            title: "药店管理",
            icon: Suitcase,
            requiresAuth: released,
            hideInBreadcrumb: true
        }
    },
    {
        path: '/login',
        name: '登录',
        component: Login,
        meta: {
            title: "登录",
            requiresAuth: false,
            hidden: true
        }
    },
];

// 创建路由实例
const router = createRouter({
    history: createWebHistory(),
    routes, // （缩写）相当于 routes: routes
});
// 全局前置守卫：拦截路由请求
router.beforeEach(async (to, from, next) => {
    const authStore = useAuthStore()

    // 1. 如果是需要登录的页面，且当前状态为未登录，但 localStorage 有 token（说明是刷新页面）
    if (to.meta.requiresAuth && !authStore.isAuthenticated && localStorage.getItem('token')) {
        // 从 localStorage 恢复 token 到 Pinia 状态
        authStore.token = localStorage.getItem(TOKEN_KEY)
        authStore.isAuthenticated = true
        // 尝试获取用户信息（恢复登录状态）
        await authStore.fetchUserInfo()
    }

    // 2. 正常的路由权限判断
    if (to.meta.requiresAuth && !authStore.isAuthenticated) {
        next('/login')
    } else {
        next()
    }
});
export default router;